﻿using Abp.Dependency;
using Abp.Domain.Repositories;
using Batman.Core.Utils;
using Batman.Jianbei.Forum.Areas.ChatRoom;
using Batman.Jianbei.Forum.Core.ChatRoom;
using Batman.Jianbei.Forum.Core.Datas;
using Batman.Jianbei.Forum.Repositories.Mongo;
using Microsoft.EntityFrameworkCore;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Linq;
using System.Text;

namespace Batman.Jianbei.Forum.Areas.ChatRoom
{
    public class SendTextMQ : MQBase, ISingletonDependency
    {
        public static readonly string ExchangeName = "TREE_HOLE_TEXT_MSG_EXCHANGE";

        public static readonly string QueuenName = "TREE_HOLE_TEXT_MSG_QUEUN";

        public static readonly string RouterKey = string.Empty;

        private static EventingBasicConsumer _consumer;

        public SendTextMQ() : base()
        {
            _channel.ExchangeDeclare(ExchangeName, ExchangeType.Fanout, false, false, null);
            _channel.QueueDeclare(QueuenName, false, false, false, null);
            _channel.QueueBind(QueuenName, ExchangeName, string.Empty, null);

            _consumer = new EventingBasicConsumer(_channel);

            _consumer.Received += _consumer_Received;

            //启动消费者 设置为手动应答消息
            _channel.BasicConsume(QueuenName, false, _consumer);
        }

        private void _consumer_Received(object sender, BasicDeliverEventArgs e)
        {
            var _textHisCollection = IocManager.Instance.Resolve<MongoRepositoryBase<MsgHis>>();
            var _roomMaskRepo = IocManager.Instance.Resolve<IRepository<RoomMask, string>>();

            var message = Encoding.UTF8.GetString(e.Body);
            var sendTextMQInput = JsonUtil.Deserialize<SendTextMQInput>(message);
            using (var ctx = new ChatRoomDbFactory().CreateDbContext(null))
            {
                var query = ctx.RoomMask.AsNoTracking().Include(t => t.Mask).ThenInclude(t => t.Avatar).AsQueryable();
                var roomMask = query.FirstOrDefault(t => t.RoomId == sendTextMQInput.RoomId && t.Uid == sendTextMQInput.UId);
                if (roomMask == null || roomMask.NotEntry)
                {
                    // todo: 记录日志
                    return;
                }

                // 记录下聊天记录
                _textHisCollection.Insert(new TextHis(sendTextMQInput.UId, sendTextMQInput.RoomId, roomMask.Mask, sendTextMQInput.Text));

                _channel.BasicAck(e.DeliveryTag, false);
            }


        }

        public void BasicPublish<T>(T body)
        {
            var bodyString = JsonUtil.Serialize(body);
            var bodyBytes = Encoding.UTF8.GetBytes(bodyString);
            BasicPublish(bodyBytes);
        }

        private void BasicPublish(byte[] body)
        {
            _channel.BasicPublish(ExchangeName, RouterKey, null, body);
        }
    }
}
